package llama.view.panels;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;

import llama.core.IUser;
import llama.ctrl.ControllerFactory;
import llama.ctrl.ConversationCtrl;
import llama.ctrl.ConversationCtrl.ConversationOption;

public class ClosableTabPanel extends JPanel implements ActionListener, MouseListener {
	private JLabel lblHeader;
	private final IUser user;
	
	/**
	 * Create the panel.
	 * @param user2 
	 */
	public ClosableTabPanel(final IUser user) {
		this.user = user;
		
		setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
		
		lblHeader = new JLabel(user.getFullName());
		lblHeader.setFont(new Font("Trebuchet MS", Font.PLAIN, 14));
		add(lblHeader);
		
		add(Box.createHorizontalStrut(3));
		
		JButton btnClose = new JButton();
		btnClose.setBorderPainted(false);
		btnClose.setBorder(BorderFactory.createLineBorder(Color.lightGray, 1));
				
		btnClose.setIcon(new ImageIcon("img//close.png")); //TODO: resource mapping
		btnClose.setPressedIcon(new ImageIcon("img//closePressed.png"));
		btnClose.addActionListener(this);
		add(btnClose);
		
		this.addMouseListener(this);

	}
	
	private void closeConversation() {
		ConversationCtrl conversationCtrl = (ConversationCtrl) ControllerFactory.getController(ConversationCtrl.class);
		conversationCtrl.setSelectedContact(ConversationOption.CLOSE, user);
		conversationCtrl.execute();
	}

	private void selectConversation() {
		ConversationCtrl conversationCtrl = (ConversationCtrl) ControllerFactory.getController(ConversationCtrl.class);
		conversationCtrl.setSelectedContact(ConversationOption.SELECT, user);
		conversationCtrl.execute();
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		closeConversation();
	}

	public void highlight() {
		lblHeader.setForeground(new Color(9,205,218));
	}
	
	public void deHighlight() {
		lblHeader.setForeground(Color.black);
	}

	@Override
	public void mouseClicked(MouseEvent e) {
		if(e.getButton() == MouseEvent.BUTTON1) {
			selectConversation();
		}
		else if(e.getButton() == MouseEvent.BUTTON2) {
			closeConversation();
		}
	}

	@Override
	public void mouseEntered(MouseEvent e) {}

	@Override
	public void mouseExited(MouseEvent e) {}

	@Override
	public void mousePressed(MouseEvent e) {}

	@Override
	public void mouseReleased(MouseEvent e) {}

}
